//
//  WimmelListViewController.m
//  Lextra Junior ueb IT
//
//  Created by Dirk Lieder on 27.05.11.
//  Copyright 2011 Phosphon. All rights reserved.
//
#define RGB(r, g, b) \
[UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

#import "WimmelListViewController.h"
#import "Lextra_Engine.h"
#import "NavigationViewController.h"
#import "AsyncImageView.h"


@implementation WimmelListViewController

@synthesize myTableView;
@synthesize woerPre;
@synthesize navigationBar;
NSMutableArray *listData; // list


AVAudioPlayer *audioPlayer;
NSInteger myNumber;


- (void)setDelegatePlud:(id)new_delegate para:(NSArray *)para{
	Delegate = new_delegate;
    
    NSArray *listDataIn;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        listDataIn = [woerPre getWimmelListPoinds:[(NSDictionary*)para objectForKey:@"wimmelbild"]];
    }
    else
    {
        listDataIn = [Delegate getWimmelListPoinds:[(NSDictionary*)para objectForKey:@"wimmelbild"]];
    }
    
    // get list poinds
    if(listData) [listData release];
    listData = [[NSMutableArray alloc] initWithArray:listDataIn copyItems:YES];

    
    // sort Array 
    [listData sortUsingFunction:sortNum context: nil];

    if([[[listData objectAtIndex:0] objectForKey:@"wimmelnummer"] intValue] == 0){
        myNumber = 0;
        
        [self playIt];
        [listData removeObjectAtIndex:0];
    }
    //__NGUYEN__HUY_SON
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        CGFloat navBarHeight = 44.0f;    
        CGRect frame = CGRectMake(0, 0, navigationBar.frame.size.width, navBarHeight);
        [navigationBar setFrame:frame];
    }  //___END_NGUYEN_HUY_SON
    [self aktDisplay];
    
}

-(void)playIt{
    
    if(audioPlayer) [audioPlayer stop];
    
    NSDictionary *myPoindInfo = [listData objectAtIndex:myNumber];
    
    
    NSString *myFilename;
    NSMutableString *myName = [[NSMutableString alloc] initWithString:[myPoindInfo objectForKey:@"ton"]];
    
    if([myName hasSuffix:@".mp3"]){
        myFilename = [myName substringToIndex:[myName length]-4];
    } else {
        myFilename = [[NSString alloc] initWithString:myName];
    }
    
    if(myName){
        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:myFilename ofType:@"m4a"]]; 
        if(audioPlayer) {
            [audioPlayer stop];
            [audioPlayer release];
        }
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        audioPlayer.delegate = self;
        if(audioPlayer) [audioPlayer stop];
        [audioPlayer play];
    }
    
    
}

// akt display
- (void)aktDisplay{
    [myTableView reloadData];
     NSIndexPath *indPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [myTableView scrollToRowAtIndexPath:indPath atScrollPosition:UITableViewScrollPositionTop animated:false];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        NSLog(@"WimmelListViewController - initWithNibName: %@", self.view.subviews);
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    // Build the array static  
    listData = [[NSMutableArray alloc] init];
        
	//[listData addObject:[[NSDictionary alloc] initWithObjectsAndKeys:@"liste", @"typ",@"Colori" , @"name", @"Farben", @"beschreibung", @"", @"bild", @"1", @"target", nil]];

    
    // Show the string values  
    // for (NSString *str in listData)
    //    NSLog(@"--%@", str);
    
    [myTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [myTableView reloadData];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        [navigationBar setTintColor:[[UIColor alloc] initWithRed:20.0 / 255 green:59.0 / 255 blue:102.0 / 255 alpha:1.0]];

        CGFloat navBarHeight = 44.0f;    
        CGRect frame = CGRectMake(0, 0, navigationBar.frame.size.width, navBarHeight);
        [navigationBar setFrame:frame];
        if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait ){
            myTableView.frame = CGRectMake(0, 44, 768, 1004);
            self.view.frame  = CGRectMake(0, 0, 768, 1024);
        }
        else {
            self.view.frame  = CGRectMake(0, 0,1024, 768);
            myTableView.frame = CGRectMake(0, 44, 703, 768);
        }
        NSLog(@"WimmelListViewController - viewDidLoad: %@", self.view.subviews);
    }  //___END_NGUYEN_HUY_SON

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if( [UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait ){
        myTableView.frame = CGRectMake(0, 44, 768, 1004);
        self.view.frame  = CGRectMake(0, 0, 768, 1024);
    }
    else {
        self.view.frame  = CGRectMake(0, 0,1024, 768);
        myTableView.frame = CGRectMake(0, 44, 703, 768);
    }
    NSLog(@"WimmelListViewController - viewWillAppear: %@", self.view.subviews);
}

#pragma mark - tableView

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{	
    return 100;			
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [listData count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	
	NSUInteger row = [indexPath row];
	UITableViewCell *cell;
	
	static NSString *CustomCellIdentifier;
    
    // Eintrag
    CustomCellIdentifier = @"part1";
    cell = [tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
    if (cell == nil) {
        // new cell
        cell = [self getCell:CustomCellIdentifier];
    }
    
    NSDictionary *Pointer = [listData objectAtIndex:row];
    
    
    UILabel *descriptionLabel = (UILabel*)[cell.contentView viewWithTag:1];
    
    
    NSMutableString *tmpString1 = [[NSMutableString alloc] initWithString:[Pointer objectForKey:@"artikel"]];
    
    if([tmpString1 length] > 0){
        if(![tmpString1 hasSuffix:@"'"]){
            [tmpString1 appendString:@" "];
        }
    }
    
    if([[[NSMutableString alloc] initWithString:[Pointer objectForKey:@"origFR"]] length] !=0){
        [tmpString1 appendString:[Pointer objectForKey:@"origFR"]]; 
    } else {
        [tmpString1 appendString:[Pointer objectForKey:@"bezeichnungFR"]]; 
    }
    
    
    NSMutableString *tmpString2;
    if([[[NSMutableString alloc] initWithString:[Pointer objectForKey:@"origDE"]] length] !=0){
        tmpString2 = [[NSMutableString alloc] initWithString:[Pointer objectForKey:@"origDE"]];
    } else {
        tmpString2 = [[NSMutableString alloc] initWithString:[Pointer objectForKey:@"bezeichnungDE"]];
    }
    
    
    if([tmpString2 length] ==0)tmpString2 = [[NSMutableString alloc] initWithString:[Pointer objectForKey:@"bezeichnungDE"]];

            
    descriptionLabel.frame = CGRectMake(100, 18, 195, 50);
    descriptionLabel.text = tmpString1;
    CGSize expectedLabelSize = [descriptionLabel.text sizeWithFont:descriptionLabel.font 
                                                 constrainedToSize:descriptionLabel.frame.size
                                                     lineBreakMode:UILineBreakModeWordWrap];
    descriptionLabel.frame = CGRectMake(100, 18, 195, expectedLabelSize.height);
    

    
    UILabel *descriptionLabel2 = (UILabel*)[cell.contentView viewWithTag:2];    

    descriptionLabel2.frame = CGRectMake(100, 18, 195, 50);
    descriptionLabel2.text = tmpString2;

    CGSize expectedLabelSize2 = [descriptionLabel2.text sizeWithFont:descriptionLabel2.font 
                                                   constrainedToSize:descriptionLabel2.frame.size
                                                       lineBreakMode:UILineBreakModeWordWrap];
    descriptionLabel2.frame = CGRectMake(100, 18, 195, expectedLabelSize2.height);
    descriptionLabel2.center = CGPointMake(descriptionLabel2.center.x, descriptionLabel.bounds.size.height+18 + descriptionLabel2.bounds.size.height/2  );
    
    
    AsyncImageView *descriptionImage = (AsyncImageView*)[cell.contentView viewWithTag:3];
        
    NSMutableString *myName = [[NSMutableString alloc] initWithString:[Pointer objectForKey:@"bild"]];
                               
    NSString *substring;
    if([myName length] > 2){
        if([myName hasSuffix:@".tif"]){
            substring = [[myName substringToIndex:[myName length]-4] stringByAppendingString:@"_k"];
        } else {
            substring = [myName stringByAppendingString:@"_k"];
        }
    } else {
        substring = [[NSString alloc] initWithString:@"pirat_k"];
    }
    //NSLog(@"laenge *%@*%d", myName,[myName length]);
    
    [descriptionImage asyncImageLoad:substring];
    
    
    return cell;
}



#pragma mark -
#pragma mark Table Delegate Methods 


-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    return indexPath; 
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSInteger row = [indexPath row];
    myNumber = row;
    
    [self playIt];

	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}



#pragma mark -
#pragma mark cell creation 
-(UITableViewCell*)getCell:(NSString*)myIdentifier{
	
	// new cell
    UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myIdentifier]autorelease];
	cell.userInteractionEnabled = YES;
    cell.selectedBackgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Empty.png"]] autorelease];
    cell.selectedBackgroundView.autoresizingMask = UIViewContentModeScaleToFill;
	
	// Text Label blue
	CGRect aframe = CGRectMake(100, 18, 195, 50);
	UILabel *textLabel = [[[UILabel alloc] initWithFrame:aframe] autorelease];
	
    textLabel.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:14];
	textLabel.numberOfLines=0;
    textLabel.lineBreakMode = UILineBreakModeWordWrap;
    textLabel.textColor = RGB(0x00, 0x3f, 0x9e);
    textLabel.highlightedTextColor = RGB(0x40, 0x7f, 0xde);
	textLabel.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
	textLabel.clearsContextBeforeDrawing = YES;
	textLabel.tag = 1;
	//textLabel.frame = CGRectMake(textLabel.frame.origin.x,textLabel.frame.origin.y,320.0,textLabel.frame.size.height);
	[cell.contentView addSubview:textLabel];		
    
 	// Text Label blak
	aframe = CGRectMake(100, 18, 195, 50);
	textLabel = [[[UILabel alloc] initWithFrame:aframe] autorelease];
	
    textLabel.font = [UIFont fontWithName:@"TrebuchetMS-Italic" size:14];
	textLabel.numberOfLines=0;
    textLabel.lineBreakMode = UILineBreakModeWordWrap;
    textLabel.textColor = RGB(0x00, 0x00, 0x00);
    textLabel.highlightedTextColor = RGB(0x60, 0x60, 0x60);
	textLabel.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
	textLabel.clearsContextBeforeDrawing = YES;
	textLabel.tag = 2;
	//textLabel.frame = CGRectMake(textLabel.frame.origin.x,textLabel.frame.origin.y,320.0,textLabel.frame.size.height);
	[cell.contentView addSubview:textLabel];		
    
    // image view async
    aframe = CGRectMake(5, 5, 90,90);
    AsyncImageView *topImageView = [[[AsyncImageView alloc] initWithFrame:aframe] autorelease];
    topImageView.tag = 3;
    topImageView.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
    [cell.contentView addSubview:topImageView];	
	
    
	// trenner
    CGRect frame;
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        frame = CGRectMake(0, 99, 768,1);
    }
    else
    {
        frame = CGRectMake(0, 99, 320,1);
    }
	 
	UIImageView *trennerImageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"listtrenner.png"]] autorelease];
	trennerImageView.frame = frame;
	[cell.contentView addSubview:trennerImageView];
    
    
	cell.contentView.backgroundColor = [UIColor colorWithWhite:1.00 alpha:0.0];
    
	return cell;
}
- (void)sstop{
    if(audioPlayer) [audioPlayer stop];
}


//  MyOwnClass sort function
int sortNum( id obj1, id obj2, void *context ){
    return [[obj1 objectForKey:@"wimmelnummer"] intValue] > [[obj2 objectForKey:@"wimmelnummer"] intValue];
}



- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
    {
        return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
    }
    else
    {
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
}
//______NGUYEN_HUY_SON_________________________________________________________________________________________
#pragma mark -
#pragma mark Managing the popover

- (void)showRootPopoverButtonItem:(UIBarButtonItem *)barButtonItem {
    // Add the popover button to the toolbar.
    [navigationBar.topItem setLeftBarButtonItem:barButtonItem animated:NO];
}


- (void)invalidateRootPopoverButtonItem:(UIBarButtonItem *)barButtonItem {
    // Remove the popover button from the toolbar.
    [navigationBar.topItem setLeftBarButtonItem:nil animated:NO];
}
//___END_NGUYEN_HUY_SON________________________________________________________________________________________
@end
